package com.jeecg.xiaozhi.wxuser.service.impl;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.ApplicationContextUtil;
import org.jeecgframework.core.util.MyClassLoader;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.minidao.util.FreemarkerParseFactory;
import org.jeecgframework.web.cgform.enhance.CgformEnhanceJavaInter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeecg.xiaozhi.wxuser.entity.WxUserEntity;
import com.jeecg.xiaozhi.wxuser.service.WxUserServiceI;

@Service("wxUserService")
@Transactional
public class WxUserServiceImpl extends CommonServiceImpl implements WxUserServiceI {

	@Autowired
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	@Override
	public void delete(WxUserEntity entity) throws Exception {
		super.delete(entity);
		// 执行删除操作增强业务
		this.doDelBus(entity);
	}

	@Override
	public Serializable save(WxUserEntity entity) throws Exception {
		Serializable t = super.save(entity);
		// 执行新增操作增强业务
		this.doAddBus(entity);
		return t;
	}

	@Override
	public void saveOrUpdate(WxUserEntity entity) throws Exception {
		super.saveOrUpdate(entity);
		// 执行更新操作增强业务
		this.doUpdateBus(entity);
	}

	/**
	 * 新增操作增强业务
	 * 
	 * @param t
	 * @return
	 */
	private void doAddBus(WxUserEntity t) throws Exception {
		// -----------------sql增强 start----------------------------
		// -----------------sql增强 end------------------------------

		// -----------------java增强 start---------------------------
		// -----------------java增强 end-----------------------------
	}

	/**
	 * 更新操作增强业务
	 * 
	 * @param t
	 * @return
	 */
	private void doUpdateBus(WxUserEntity t) throws Exception {
		// -----------------sql增强 start----------------------------
		// -----------------sql增强 end------------------------------

		// -----------------java增强 start---------------------------
		// -----------------java增强 end-----------------------------
	}

	/**
	 * 删除操作增强业务
	 * 
	 * @param id
	 * @return
	 */
	private void doDelBus(WxUserEntity t) throws Exception {
		// -----------------sql增强 start----------------------------
		// -----------------sql增强 end------------------------------

		// -----------------java增强 start---------------------------
		// -----------------java增强 end-----------------------------
	}

	private Map<String, Object> populationMap(WxUserEntity t) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", t.getId());
		map.put("openid", t.getOpenid());
		map.put("nickname", t.getNickName());
		map.put("gender", t.getGender());
		map.put("language", t.getLanguage());
		map.put("city", t.getCity());
		map.put("province", t.getProvince());
		map.put("country", t.getCountry());
		map.put("avatarurl", t.getAvatarUrl());
		map.put("createdate", t.getCreatedate());
		map.put("status", t.getStatus());
		map.put("phonenum", t.getPhonenum());
		map.put("idcardno", t.getIdcardno());
		map.put("realname", t.getRealname());
		map.put("issmz", t.getIssmz());
		map.put("session_key", t.getSessionKey());
		map.put("code", t.getCode());
		return map;
	}

	/**
	 * 替换sql中的变量
	 * 
	 * @param sql
	 * @param t
	 * @return
	 */
	public String replaceVal(String sql, WxUserEntity t) {
		sql = sql.replace("#{id}", String.valueOf(t.getId()));
		sql = sql.replace("#{openid}", String.valueOf(t.getOpenid()));
		sql = sql.replace("#{nickname}", String.valueOf(t.getNickName()));
		sql = sql.replace("#{gender}", String.valueOf(t.getGender()));
		sql = sql.replace("#{language}", String.valueOf(t.getLanguage()));
		sql = sql.replace("#{city}", String.valueOf(t.getCity()));
		sql = sql.replace("#{province}", String.valueOf(t.getProvince()));
		sql = sql.replace("#{country}", String.valueOf(t.getCountry()));
		sql = sql.replace("#{avatarurl}", String.valueOf(t.getAvatarUrl()));
		sql = sql.replace("#{createdate}", String.valueOf(t.getCreatedate()));
		sql = sql.replace("#{status}", String.valueOf(t.getStatus()));
		sql = sql.replace("#{phonenum}", String.valueOf(t.getPhonenum()));
		sql = sql.replace("#{idcardno}", String.valueOf(t.getIdcardno()));
		sql = sql.replace("#{realname}", String.valueOf(t.getRealname()));
		sql = sql.replace("#{issmz}", String.valueOf(t.getIssmz()));
		sql = sql.replace("#{session_key}", String.valueOf(t.getSessionKey()));
		sql = sql.replace("#{code}", String.valueOf(t.getCode()));
		sql = sql.replace("#{UUID}", UUID.randomUUID().toString());
		return sql;
	}

	/**
	 * 执行JAVA增强
	 */
	private void executeJavaExtend(String cgJavaType, String cgJavaValue, Map<String, Object> data) throws Exception {
		if (StringUtil.isNotEmpty(cgJavaValue)) {
			Object obj = null;
			try {
				if ("class".equals(cgJavaType)) {
					// 因新增时已经校验了实例化是否可以成功，所以这块就不需要再做一次判断
					obj = MyClassLoader.getClassByScn(cgJavaValue).newInstance();
				} else if ("spring".equals(cgJavaType)) {
					obj = ApplicationContextUtil.getContext().getBean(cgJavaValue);
				}
				if (obj instanceof CgformEnhanceJavaInter) {
					CgformEnhanceJavaInter javaInter = (CgformEnhanceJavaInter) obj;
					javaInter.execute("wx_user", data);
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new Exception("执行JAVA增强出现异常！");
			}
		}
	}

	private void executeSqlEnhance(String sqlEnhance, WxUserEntity t) {
		Map<String, Object> data = populationMap(t);
		sqlEnhance = ResourceUtil.formateSQl(sqlEnhance, data);
		boolean isMiniDao = false;
		try {
			data = ResourceUtil.minidaoReplaceExtendSqlSysVar(data);
			sqlEnhance = FreemarkerParseFactory.parseTemplateContent(sqlEnhance, data);
			isMiniDao = true;
		} catch (Exception e) {
		}
		String[] sqls = sqlEnhance.split(";");
		for (String sql : sqls) {
			if (sql == null || sql.toLowerCase().trim().equals("")) {
				continue;
			}
			int num = 0;
			if (isMiniDao) {
				num = namedParameterJdbcTemplate.update(sql, data);
			} else {
				num = this.executeSql(sql);
			}
		}
	}
}